package com.xiang.encodetool.service;

import com.xiang.encodetool.filter.MyFileFilter;
import com.xiang.encodetool.util.FileEncodeUtil;
import com.xiang.encodetool.util.UTF8Parser;
import javafx.concurrent.Task;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.awt.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by xiangliyou on 17-8-5.
 *
 * @DESCRIPTION 事务处理类
 */
public class Handler {
    //显示的舞台
    private Stage stage;
    //文件选择器
    private final FileChooser fileChooser = new FileChooser();
    //目录选择器
    private final DirectoryChooser directoryChooser = new DirectoryChooser();
    //文件列表
    private List<File> fileList = new ArrayList<>();
    private List<String > fileEncodeList = new ArrayList<>();

    public Handler(Stage primaryStage) {
        this.stage = primaryStage;
    }

    /**
     * 弹出文件选择框
     * @return 选择了的文件名数组
     */
    public String[]  choiceFile() {
        //返回的文件名数组
        String[] fileNames = new String[0];

        //配置文件选择框
        configureFileChooser(fileChooser);
        //打开文件选择框
        List<File> files = fileChooser.showOpenMultipleDialog(stage);
        fileList = new ArrayList<>(files);

        /**过滤文件***/
        filterFile();

        fileNames = new String[fileList.size()];
        for (int i = 0; i < fileList.size(); i++) {
            fileNames[i] = fileList.get(i).getName();
        }
        return fileNames;
    }

    /**
     * 配置文件选择器
     * @param fileChooser 文件选择器
     */
    private void configureFileChooser(FileChooser fileChooser) {
        fileChooser.setTitle("选择要转换的文件");
        fileChooser.setInitialDirectory(
                new File(System.getProperty("user.home"))
        );
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("JAVA", "*.java"),
                new FileChooser.ExtensionFilter("TXT", "*.txt"),
                new FileChooser.ExtensionFilter("C", "*.c"),
                new FileChooser.ExtensionFilter("CPP", "*.cpp"),
                new FileChooser.ExtensionFilter("All Text Files", "*.*")
        );
    }

    /**
     * 处理转码
     * @return 处理的任务task，主要用于更新进度条显示
     */
    public Task start(String targetEncode) {
        System.out.println(Arrays.toString(fileList.toArray()));
        //保存文件的路径
        String savePath = fileList.get(0).getPath() + System.currentTimeMillis();
        File saveDir = new File(savePath);
        if (!saveDir.exists()) {
            saveDir.mkdir();
        }
        //创建转码任务
        Task task = new Task() {
            int max = fileList.size();
            @Override
            protected Object call() throws Exception {
                for (int i = 0; i < fileList.size(); i++) {
                    //配置解码器
                    String curEncode = fileEncodeList.get(i);
                    UTF8Parser utf8Parser;
                    if (curEncode != null) {
                        utf8Parser = new UTF8Parser(curEncode, targetEncode);
                    } else {
                        utf8Parser = new UTF8Parser("gbk", targetEncode);
                    }
                    utf8Parser.parse(new File[]{fileList.get(i)}, savePath);

                    updateProgress(i, max);
                }
                return null;
            }
        };
        //开始转码
        new Thread(task).start();

        return task;
    }

    public String[] choiceDir() {
        //返回的文件名数组
        String[] fileNames = new String[0];

        //配置文件选择框
        configureDirChooser(directoryChooser);
        //打开文件选择框
        File parentDir = directoryChooser.showDialog(stage);
        //遍历所选的目录,过滤不需要的文件
        openDir(parentDir);

        if (fileList != null) {
            fileNames = new String[fileList.size()];
            for (int i = 0; i < fileList.size(); i++) {
                fileNames[i] = fileList.get(i).getName();
            }
        }
        return fileNames;
    }

    /**
     * 遍历所选的目录，可能选择的目录比较大，新开启一个线程来处理
     * @param parentDir 要搜索的目录
     */
    private void openDir(File parentDir) {

    }

    private void configureDirChooser(DirectoryChooser directoryChooser) {
        directoryChooser.setTitle("选择要转换的文件所在的目录");
        fileChooser.setInitialDirectory(
                new File(System.getProperty("user.home"))
        );
    }

    /***
     * 文件过滤，只选择文本文件
     */
    private void filterFile() {
        fileEncodeList.clear();
        for (int i = 0; i < fileList.size(); i++) {
            File file = fileList.get(i);
            //跳过常见的视频/音频/图像文件
            boolean isTextFile = MyFileFilter.simpleNotTextFileFilter(file.getName());
            if (!isTextFile) {
               // fileList.remove(file);
                fileList.remove(fileList.indexOf(file));
                break;
            }
            //调用过滤工具
            String charset = FileEncodeUtil.getCharset(file);
            if (charset == null) {
                fileList.remove(file);
            } else {
                fileEncodeList.add(i, charset);
                System.out.println(fileList + "-----" +charset);
            }
        }
    }
}
